const express = require('express')
const router = express.Router()
const Course = require('../models').Course
const config = require('../config')
const pFormidable = require('../utility/formidable')
const path = require('path')
const gm = require('gm')

// get all
// query { pageSize, pageNumber }
router.get('/adverts', (req, res, next) => {

})

// add
router.post('/courses', (req, res, next) => {
  const body = req.body
  const course = new Course({
    title: body.title,
    create_id: req.session.manager._id
  })
  course.save()
    .then((course) => {
      res.json({
        success: true,
        ret: {
          course_id: course._id
        }
      })
    })
    .catch(err => {
      next(err)
    })
})

// 专门用来处理图片裁切，然后持久化到数据库
router.get('/courses/:id/manage/picture', (req, res, next) => {
  let { height, width, x, y, image } = req.query
  const pathObj = path.parse(image)
  image = path.join(config.uploadDir, path.basename(image))
  const writeFilePath = path.join(config.courseDir, pathObj.name + Math.random().toString().substr(2) + pathObj.ext)
  gm(image)
    .crop(width, height, x, y)
    .resize(304, 171)
    .write(writeFilePath, err => {
      if (err) {
        return next(err)
      }
      Course.findByIdAndUpdate(req.params.id, {
        $set: {
          image: path.basename(writeFilePath)
        }
      }).then(data => {
        res.json({
          success: true,
          ret: {
            course_image: '/api/uploads/course/' + path.basename(writeFilePath)
          }
        })
      })
    })
})

// findById
router.get('/courses/:id', (req, res, next) => {
  const courseId = req.params.id
  Course.findById(courseId)
    .then(course => {
      res.json({
        success: true,
        ret: {
          course
        }
      })
    })
    .catch(err => {
      next(err)
    })
})

// 一张图片：要裁切的参数
// router.post('/courses/:id/manage/picture')

// 更新所有字段（需要客户端提供完整信息数据）
router.patch('/courses/:id', (req, res, next) => {
  console.log(req.params.id)
  const body = req.body
  Course.findByIdAndUpdate(req.params.id, {
      $set: {
        title: body.title,
        description: body.description,
        sub_category_id: body.sub_category_id,
        top_category_id: body.top_category_id,
        tags: body.tags
      }
    }).then(() => {
      res.json({
        success: true,
        ret: {}
      })
    })
    .catch(err => {
      next(err)
    })
})

module.exports = router
